package com.topscomm.mpm.cboController;

import com.topscomm.basic.util.Config;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.controller.ICboApprovalNodeInsController;
import com.topscomm.cbo.controller.auto.CboApprovalNodeInsControllerAuto;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst.TapApprovalNodeStateEnum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("cbo/approvalNodeIns")
public class CboApprovalNodeInsController extends CboApprovalNodeInsControllerAuto
		implements ICboApprovalNodeInsController {
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_flowid")) {
			String value = paraMap.get("qry_flowid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and flowid = {0} ", value);
		}
		if (paraMap.containsKey("qry_flowinsid")) {
			String value = paraMap.get("qry_flowinsid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and flowinsid = {0} ", value);
		}
		if (paraMap.containsKey("qry_nodeid")) {
			String value = paraMap.get("qry_nodeid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and nodeid = {0} ", value);
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = {0} ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_startdate1")) {
			String value = paraMap.get("qry_startdate1").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and startdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_startdate2")) {
			String value = paraMap.get("qry_startdate2").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and startdate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_approvaluserid")) {
			String value = paraMap.get("qry_approvaluserid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaluserid = {0} ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state = {0} ", value);
		}
		if (paraMap.containsKey("qry_maintitle")) {
			String value = paraMap.get("qry_maintitle").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and maintitle like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_approvalopinion")) {
			String value = paraMap.get("qry_approvalopinion").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvalopinion like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_approvaldate1")) {
			String value = paraMap.get("qry_approvaldate1").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaldate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_approvaldate2")) {
			String value = paraMap.get("qry_approvaldate2").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and approvaldate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_approvalOpinionIsNotNull")
				&& "true".equals(paraMap.get("qry_approvalOpinionIsNotNull").toString())) {
			sql.appendSingle(" and  not (approvalexplain='' or approvalexplain is null) ");
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0} ", value);
		}
		if (paraMap.containsKey("qry_approvalOpinion")
				&& !StringUtil.isEmpty(paraMap.get("qry_approvalOpinion").toString())) {
			sql.appendSingle(" and ApprovalOpinion like '%{0}%' ", paraMap.get("qry_approvalOpinion").toString());
		}
		if (paraMap.containsKey("qry_approvalUserId")
				&& !StringUtil.isEmpty(paraMap.get("qry_approvalUserId").toString())) {
			sql.appendSingle(" and ApprovalUserId = '{0}' ", paraMap.get("qry_approvalUserId").toString());
		}
		return sql.toString();
	}

	/**
	 * @description: 查询待审批节点的信息
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月19日下午6:23:12
	 * @modify:
	 */
	@GetMapping("/queryNodeInfo")
	public ResponseResult<Object> queryNodeInfo(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		List<Map<String, Object>> list = this.service.queryMap(paraMap, "myApprovalOne");
		if (list != null && list.size() > 0) {
			// 处于审批中
			if (TapApprovalNodeStateEnum.Approveing == ConvertUtil.convertToInt(list.get(0).get("state"))) {
				return ResponseResult.ok(list.get(0));
			} else
				return ResponseResult.error("待办数据已经被处理！");
		} else
			return ResponseResult.error("没有找到对应的待审批数据！");
	}

	/**
	 * @description:待审批列表
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月19日下午6:30:05
	 * @modify:
	 */
	@GetMapping("/queryApprovalList")
	public ResponseResult<Object> queryApprovalList(@RequestParam Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		Object[] list = paraMap.keySet().toArray();
		for (Object entry : list) {
			if (ConvertUtil.convertToString(entry).startsWith("qry_")) {
				if (StringUtil.isEmpty(ConvertUtil.convertToString(paraMap.get(entry))))
					paraMap.remove(entry);
			}
		}
		paraMap.put("qry_approvaluserid", this.getUserBean().getUser().getId());
		if (!paraMap.containsKey("qry_state")) {
			paraMap.put("qry_state", 1);
		}
		// 待审批单据的来源系统在config.properties中配置 --李正亮 2019-1-8 add
//		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
//		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
//		for (String approval : approvals) {
//			qry_where = qry_where + " flowins.sourcetype like '" + approval + "%' or ";
//		}
//		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		qry_where = qry_where + "flowins.sourcetype like 'Mpm%')";
		paraMap.put("qry_where", qry_where);
		int totalCount = service.getCount(paraMap, "myApprovalCount");
		//houyuhang 2021-08-12添加 判断是否有分页，若没有分页，则返回所有可用信息
		List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
		if(paraMap.containsKey("pageSize")){
			tempList = service.queryMapForPage(query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord(), paraMap, "myApprovalList");
		}else {
			tempList = service.queryMapForPage(paraMap, "myApprovalListNoPage");
		}
		service.setDispFields(tempList);// fanzhiming 2018-09-12增加
		// 审批节点名称修改为从extendfield2字段取值，解决自循环竞争节点名称细化问题
		for (Map<String, Object> tempDataMap : tempList) {
			if (tempDataMap.get("extendfield2") != null
					&& !StringUtil.isEmpty(tempDataMap.get("extendfield2").toString())) {
				tempDataMap.put("dispnodeid", tempDataMap.get("extendfield2").toString());
			}
		}
		Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}

	/**
	 * @description:待审批列表中，各个审批类型数量查询
	 * @param paraMap
	 * @return
	 * @author: zhanglongfei
	 * @date: 2020年3月23日下午2:08:54
	 * @modify:
	 */
	@GetMapping("/querySouceTypeCount")
	public ResponseResult<Object> querySouceTypeCount(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 待审批单据的来源系统在config.properties中配置
		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
		String qry_wherecode = " (";
		for (String approval : approvals) {
			qry_where = qry_where + " sourcetype like '" + approval + "%' or ";
			qry_wherecode = qry_wherecode + " code like '" + approval + "%' or ";
		}
		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		qry_wherecode = qry_wherecode.substring(0, qry_wherecode.length() - 3) + ")";
		List<Map<String, Object>> sourcetypeList = datacodeCache.getCodeListMap("CboApprovalFlowCategory", qry_wherecode, "sortcode");
		List<Map<String, Object>> resultList = service.selectExecute("select " + SQLAdapter.isNull("sourcetype", "'unknown'")
				+ " as code,count(1) as count from CboApprovalNodeins where state=1 and approvaluserid ='"
				+ this.getUserBean().getUser().getId() + "' and enabled=1 " + qry_where
				+ "group by sourcetype order by count desc");
		for (Map<String, Object> type : sourcetypeList) {
			boolean isHave = false;
			for (Map<String, Object> item : resultList) {
				if (type.get("code").toString().equals(item.get("code").toString())) {
					item.put("name", type.get("name"));
					isHave = true;
					break;
				}
			}
			if (!isHave) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", type.get("code"));
				map.put("name", type.get("name"));
				map.put("count", 0);
				resultList.add(map);
			}
		}
		return ResponseResult.ok(resultList);
	}

	/**
	 * @author
	 * @date 2019年9月6日
	 * @description 首页portal树形类别
	 * @return
	 */
	@GetMapping("/querySouceTypeTree")
	public ResponseResult<Object> querySouceTypeTree(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		// 待审批单据的来源系统在config.properties中配置
		String approvalSourceSystem = Config.getInstance().getValue("ApprovalSourceSystem", "Top");
		String[] approvals = approvalSourceSystem.split(",");
		String qry_where = " and (";
		for (String approval : approvals) {
			qry_where = qry_where + " sourcetype like '" + approval + "%' or ";
		}
		qry_where = qry_where.substring(0, qry_where.length() - 3) + ")";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> resultList = service.selectExecute("select " + SQLAdapter.isNull("sourcetype", "'unknown'")
				+ " as code,extendfield2 as name,count(1) as count from CboApprovalNodeins  where state=1 and approvaluserid ='"
				+ getUserBean().getUser().getId()
				+ "' and enabled=1 " + qry_where
				+ " group by sourcetype,extendfield2 having count(1)>0 order by sourcetype,count desc");
		List<Map<String, Object>> codeList = datacodeCache.getCodeListMap("CboApprovalFlowCategory", "", "sortcode");
		for (Map<String, Object> result : resultList) {
			Map<String, Object> parent = null;
			for (Map<String, Object> item : list) {
				if (item.containsKey("pcode") && result.get("code").toString().equals(item.get("pcode").toString())) {
					parent = item;
					break;
				}
			}
			if (parent == null) {
				parent = new HashMap<String, Object>();
				parent.put("code", result.get("code"));
				parent.put("pcode", result.get("code"));
				parent.put("name", result.get("code"));
				for (Map<String, Object> code : codeList) {
					if (result.get("code").toString().equals(code.get("code").toString())) {
						parent.put("name", code.get("name"));
						break;
					}
				}
				parent.put("count", result.get("count"));
				list.add(parent);
			} else {
				parent.put("count", Integer.parseInt(result.get("count").toString())
						+ Integer.parseInt(parent.get("count").toString()));
			}
			list.add(result);
		}
		return ResponseResult.ok(list);
	}


	@Override
	@GetMapping(value = "/list")
	public ResponseResult<Object> list(@RequestParam(required = false)Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			int totalCount = this.service.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			Map<String, Object> paraMap2 = new HashMap<>();
			int begincount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",begincount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getApprovalForPage1");
			} else
				tempList = this.service.queryMap(paraMap2,"getApprovalWhere1");
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	  * @description:
	  * @author xinfushuo
	  * @param
	  * @throws
	  * @return
	  * @date 2021/8/27
	  * @modify
	  */
	private String spellListSqlForProject(Map<String,Object> paraMap){
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		sql.appendSingle("and approvaluserid = {0}",this.getUserBean().getUser().getId());
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_projectmanagercode")) {
			String value = paraMap.get("qry_projectmanagercode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagercode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and  {0} ", value);
		}
		return sql.toString();
	}
	/**
	  * @description 获取当前所有待审批的单据
	  * @author xinfushuo
	  * @param paraMap
	  * @throws
	  * @return
	  * @date 2021/8/27
	  * @modify
	  */
	@GetMapping(value = "/getApprovalAll")
	public ResponseResult<Object> getApprovalAll(@RequestParam(required = false) Map< String,Object> paraMap ) {
		try {
			Map<String,Object> res = new HashMap<>();

			//准备sqlwhere 条件 如  projectcode  Approvaluserid
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSqlForProject(paraMap);
			//准备查询条件 排序依据 升降 以及最关键的sourcetype
			Map<String, Object> paraMapForQuery = new HashMap<>();

			paraMapForQuery.put("whereSql", sqlWhere);
			boolean illegalArg =  !paraMap.containsKey("sidx")||!paraMap.containsKey("sord")||!paraMap.containsKey("sourcetype");
			if(!illegalArg) {
				paraMapForQuery.put("sidx", paraMap.get("sidx"));
				paraMapForQuery.put("sord", paraMap.get("sord"));
				paraMapForQuery.put("sourcetype", paraMap.get("sourcetype"));
			}else{
				throw new Exception("参数缺失，请联系管理员！");
			}
			//查询
			List<Map<String, Object>> tempList = null;
			tempList = this.service.queryMap(paraMapForQuery, "getApprovalAll");
			//补充disp和相关信息
			//放进map返回
			this.service.setDispFields(tempList);
			int totalCount = tempList.size();
			res.put("approvalAllList",tempList);
			res.put("totalCount",totalCount);
			return ResponseResult.ok(res);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	  * @description 获取当前待审批单据总数
	  * @author xinfushuo
	  * @param paraMap
	  * @throws
	  * @return
	  * @date 2021/8/27
	  * @modify
	  */
	@GetMapping(value = "/getApprovalAllCount")
	public ResponseResult<Object> getApprovalCountAll(@RequestParam(required = false)Map<String,Object> paraMap) {
		try {
			List<Map<String,Object>> res = new ArrayList<>();
			//准备sqlwhere 条件 如  projectcode
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String sqlWhere = this.spellListSqlForProject(paraMap);
			Map<String, Object> paraMapForQueryMap = new HashMap<>();
			paraMapForQueryMap.put("whereSql", sqlWhere);
			if (paraMap.containsKey("sourcetype")) {
				String sourcetype = paraMap.get("sourcetype").toString();
				if (!StringUtil.isEmpty(sourcetype)) {
					String[] sourcetypeList = sourcetype.split(",");
					for (String type : sourcetypeList) {
						paraMapForQueryMap.put("sourcetype", type);
						List<Map<String, Object>> templist = this.service.queryMap(paraMapForQueryMap, "getApprovalAllCount");
						res.add(templist.get(0));
					}
				}
			} else {
				throw new IllegalArgumentException("缺少参数，请联系管理员！");
			}
			return ResponseResult.ok(res);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
}
